package trees;

/**
 * 实现一个 Trie (前缀树)，包含 insert, search, 和 startsWith 这三个操作。
 *
 * 示例:
 *
 * Trie trie = new Trie();
 *
 * trie.insert("apple");
 * trie.search("apple");   // 返回 true
 * trie.search("app");     // 返回 false
 * trie.startsWith("app"); // 返回 true
 * trie.insert("app");
 * trie.search("app");     // 返回 true
 * 说明:
 *
 * 你可以假设所有的输入都是由小写字母 a-z 构成的。
 * 保证所有输入均为非空字符串。
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/implement-trie-prefix-tree
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 * */
public class Trie {

    class TrieNode {
        private TrieNode[] childs = new TrieNode[26];
        private boolean isEnd;

        public void put(int index){
            TrieNode node = new TrieNode();
            childs[index] = node;
        }

        public TrieNode get(int index){
            return childs[index];
        }

        public void setEnd(){
            isEnd = true;
        }

        public boolean isEnd(){
            return isEnd;
        }
    }

    TrieNode root;

    /** Initialize your data structure here. */
    public Trie() {
        root = new TrieNode();
    }

    /** Inserts a word into the trie. */
    public void insert(String word) {
        int l = word.length();
        TrieNode node = root;
        for(int i = 0; i < l; i ++){
            int index = word.charAt(i) - 'a';
            if(node.get(index) == null) {
                node.put(index);
            }
            node = node.get(index);
        }
        node.setEnd();
    }

    private TrieNode searchNode(String word){
        TrieNode node = root;
        int l = word.length();
        for(int i = 0; i < l; i ++){
            int index = word.charAt(i) - 'a';
            node = node.get(index);
            if(node == null){
                break;
            }
        }
        return node;
    }

    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode node = searchNode(word);
        return node != null && node.isEnd();
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode node = searchNode(prefix);
        return node != null;
    }

    public static void main(String[] args){
//        Trie tree = new Trie();
////        tree.insert("app");
////        tree.insert("apple");
////        System.out.println(tree.search("app"));
////        System.out.println(tree.search("apps"));
        System.out.println('Z'+32 == 'z');

    }
}
